<?php

namespace addons\WeChat\controller;

use app\common\model\Order;
use app\admin\model\order\OrderItem;
use app\admin\model\order\OrderExpress;
use think\Db;

require_once __DIR__ . '/../sdk/include.php';
class MiniOrderShipping extends Base
{
    public $mini_config;

    public $access_token;

    /**
     * 返回实例本身
     * MiniPay constructor.
     * @param null $config
     */
    public function __construct($config = null)
    {
        parent::__construct();
        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }

        $this->mini_config = [
            'appid'        => $this->config['mini_appid'],
            'appsecret'    => $this->config['mini_appsecret'],
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id'       => $this->config['mchid'],
            'mch_key'      => $this->config['key'],
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key'        => $this->config['sslkey_path'],
            'ssl_cer'        => $this->config['sslcert_path'],
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path'   => '',

            //V3部分
            'mch_v3_key'   => $this->config['key_v3'],
            'cert_public'  => $this->config['cert_public_v3'],
            'cert_private' => $this->config['cert_private_v3'],
        ];
    }

    //获取微信的AccessToken
    public function getWxAccessToken()
    {
        $WeMini = new \WeMini\Live($this->mini_config);
        return $WeMini->getWxAccessToken();
    }

    /**
     * 上送订单信息
     * @author mitu
     * @date   2023-12-07
     * @param  [type]     $order   [description]
     * @param  [type]     $express [description]
     * @param  string     $type    [description]
     * @return [type]              [description]
     */
    public function uploadShippingInfos($order, $express = null, $type = 'send')
    {
        try {
            $orderShippingInfo = new OrderShippingInfo($order);

            if ($type == 'change') {
                $uploadParams = $orderShippingInfo->getChangeShippingParams($express);
            } else {
                $uploadParams = $orderShippingInfo->getShippingParams();
            }

            $length = count($uploadParams);
            foreach ($uploadParams as $key => $params) {
                $params['delivery_mode'] = 1;
                $params['is_all_delivered'] = true;

                if ($params['logistics_type'] == 1 && count($params['shipping_list']) > 1) {
                    // 快递物流，并且
                    $params['delivery_mode'] = 2;
                }

                if ($length > 1) {
                    if ($key == ($length -1)) {
                        // 最后一条
                        $params['is_all_delivered'] = true;         // 发货完成
                    } else {
                        $params['is_all_delivered'] = false;        // 发货未完成
                    }
                }

                $params['upload_time'] = date(DATE_RFC3339);

                \think\facade\Log::error('发货信息录入' . json_encode($params));
                $result = $this->uploadShippingInfo($params);

                if ($result['errcode'] != 0) {
                    throw new \Exception('获取失败: errcode:' . $result['errcode'] . '; errmsg:' . $result['errmsg']);
                }
            }
        } catch (\Exception $e) {
            \think\facade\Log::error('发货信息录入错误'.$e->getMessage());
        }
    }

    /**
     * 将发货信息提交给微信
     * @author mitu
     * @date   2023-12-07
     * @param  [type]     $params [description]
     * @return [type]             [description]
     */
    private function uploadShippingInfo($body)
    {
        $access_token = $this->getWxAccessToken();

        $add_template_url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info";
        $query = ["access_token" => $access_token['access_token']];
        $headers = array();
        array_push($headers, "Content-Type application/json");
        $result = $this->curl($add_template_url, $body, true, $query, $headers);
        return json_decode($result, true);
    }

    /**
     * 获取微信delivery数据
     * @author mitu
     * @date   2023-12-07
     * @param  boolean    $is_force [description]
     * @return [type]               [description]
     */
    public function getDelivery($is_force = false)
    {
        if (!$is_force && cache('wechat:get_delivery_list')) {
            return true;
        }
        $access_token = $this->getWxAccessToken();
        $get_delivery_url = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/get_delivery_list";

        $body = [];
        $query = ["access_token" => $access_token['access_token']];
        $headers = array();
        array_push($headers, "Content-Type application/json");
        $result = $this->curl($get_delivery_url, $body, true, $query, $headers);
        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            throw new \Exception('获取微信 delivery 列表失败: errcode:' . $result['errcode'] . '; errmsg:' . $result['errmsg']);
        }
        // 存库
        $datas = $result['delivery_list'];
        foreach ($datas as $data) {
            $wechatExpress = WechatExpress::where('code', $data['delivery_id'])->find();
            $current = [
                'name' => $data['delivery_name'] ?? '',
                'code' => $data['delivery_id'] ?? '',
            ];
            if (!$wechatExpress) {
                $wechatExpress = new WechatExpress();
            }
            $wechatExpress->save($current);
        }
        cache('wechat:get_delivery_list', time());      // 永久有效
        return $result;
    }


    /**
     * 设置微信消息跳转路径
     * @author mitu
     * @date   2023-12-07
     * @param  boolean    $is_force [description]
     */
    public function setMessageJumpPath($is_force = false)
    {
        if (!$is_force && cache('wechat:set_message_jump_path')) {
            return true;
        }
        $access_token = $this->getWxAccessToken();
        $add_template_url = "https://api.weixin.qq.com/wxa/sec/order/set_msg_jump_path";

        $body = ['path' => 'pages/order/detail?comein_type=wechat'];
        $query = ["access_token" => $access_token['access_token']];
        $headers = array();
        array_push($headers, "Content-Type application/json");
        $result = $this->curl($add_template_url, $body, true, $query, $headers);
        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            throw new \Exception('设置微信发货消息跳转地址失败: errcode:' . $result['errcode'] . '; errmsg:' . $result['errmsg']);
        }
        cache('wechat:set_message_jump_path', time());      // 永久有效

        return $result;
    }

    /**
     * 查询是否有微信发货信息管理权限
     * @author mitu
     * @date   2023-12-07
     * @param  boolean    $is_force [description]
     * @return boolean              [description]
     */
    public function isTradeManaged($is_force = false)
    {
        $key = 'wechat:is_trade_managed';
        if (!$is_force && cache($key)) {
            return cache($key);     // 直接返回是否有权限
        }

        $access_token = $this->getWxAccessToken();
        $add_template_url = "https://api.weixin.qq.com/wxa/sec/order/is_trade_managed";

        if (!$this->config['mini_appid']) {
            // 没有配置微信小程序参数
            throw new \Exception('微信小程序发货管理查询失败，没有配置微信小程序');
        }

        $body = ['appid' => $this->config['mini_appid']];
        $query = ["access_token" => $access_token['access_token']];
        $headers = array();
        array_push($headers, "Content-Type application/json");
        $result = $this->curl($add_template_url, $body, true, $query, $headers);
        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            throw new \Exception('查询是否有微信发货信息管理权限失败: errcode:' . $result['errcode'] . '; errmsg:' . $result['errmsg']);
        }

        $is_trade_managed = intval($result['is_trade_managed']);

        cache($key, $is_trade_managed, 7200);// 缓存结果,两小时

        return $is_trade_managed;
    }

}
